<template>
  <div class="my-orders-page">
    <!-- 顶部导航 -->
    <div class="nav-header">
      <button class="back-button" @click="goBack">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
        >
          <path d="m15 18-6-6 6-6" />
        </svg>
      </button>
      <h2>我的订单</h2>
    </div>

    <!-- 订单状态标签 -->
    <div class="order-tabs">
      <div
        v-for="tab in orderTabs"
        :key="tab.value"
        class="tab"
        :class="{ active: activeTab === tab.value }"
        @click="activeTab = tab.value"
      >
        {{ tab.label }}
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="orders-container">
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <div class="loading-text">加载中...</div>
      </div>

      <div v-else-if="filteredOrders.length === 0" class="empty-orders">
        <div class="empty-icon">
          <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="1.5">
            <path d="M21 5H3a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h18a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1Z" />
            <path d="M3 9h18" />
            <path d="M7 5V3" />
            <path d="M17 5V3" />
          </svg>
        </div>
        <div class="empty-text">暂无订单</div>
        <button class="go-shopping-btn" @click="goShopping">去购物</button>
      </div>

      <div v-else class="order-list">
        <div v-for="order in filteredOrders" :key="order.ordersId" class="order-card">
          <div class="order-header">
            <div class="order-number">订单号: {{ order.orderNumber }}</div>
            <div class="order-status" :class="order.status">{{ getStatusText(order.status) }}</div>
          </div>

          <!-- 单个商品展示 -->
          <div class="order-items">
            <div class="order-item">
              <img :src="order.productImageUrl" :alt="order.productName" class="item-image">
              <div class="item-info">
                <div class="item-name">{{ order.productName }}</div>
                <div class="item-quantity">x{{ order.quantity }}</div>
              </div>
              <div class="item-price">¥{{ order.productPrice }}</div>
            </div>
          </div>

          <div class="order-footer">
            <div class="order-total">
              共{{ order.quantity }}件商品 总计: <span class="price">¥{{ order.totalPrice }}</span>
            </div>
            <div class="order-actions">
              <button
                v-if="order.status === 'pending'"
                class="action-btn pay-btn"
                @click="payOrder(order)"
              >
                去支付
              </button>
              <button
                v-if="order.status === 'shipped' || order.status === 'paid'"
                class="action-btn confirm-btn"
                @click="confirmReceipt(order)"
              >
                确认收货
              </button>
              <button
                v-if="order.status === 'delivered'"
                class="action-btn review-btn"
                @click="reviewOrder(order)"
              >
                评价
              </button>
              <button
                class="action-btn delete-btn"
                @click="openDeleteConfirm(order)"
              >
                删除订单
              </button>
              <button class="action-btn detail-btn" @click="viewOrderDetail(order)">
                订单详情
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div class="delete-confirm" v-if="showDeleteConfirm">
      <div class="confirm-dialog">
        <h3>删除订单</h3>
        <p>确定要删除该订单吗？删除后将无法恢复。</p>
        <div class="confirm-actions">
          <button class="cancel-btn" @click="showDeleteConfirm = false">取消</button>
          <button class="confirm-btn" @click="deleteOrder">确认删除</button>
        </div>
      </div>
    </div>

    <!-- 确认弹窗 -->
    <div v-if="showConfirmDialog" class="custom-dialog-overlay">
      <div class="custom-dialog">
        <div class="dialog-content">
          <p>{{ confirmDialogText }}</p>
        </div>
        <div class="dialog-actions">
          <button class="cancel-btn" @click="showConfirmDialog = false">取消</button>
          <button class="confirm-btn" @click="handleConfirm">确认</button>
        </div>
      </div>
    </div>

    <!-- Toast 提示 -->
    <div v-if="toast.show" class="custom-toast">
      {{ toast.message }}
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { getOrderList,deleteOrder as deleteOrderApi,confirmOrder } from '../api/index'

const router = useRouter()
const loading = ref(true)
const orders = ref([])
const activeTab = ref('all')
const showDeleteConfirm = ref(false)
const orderToDelete = ref(null)
const showConfirmDialog = ref(false)
const confirmDialogText = ref('')
const confirmCallback = ref(null)
const toast = ref({ show: false, message: '' })

// 订单状态标签
const orderTabs = [
  { label: '全部', value: 'all' },
  { label: '待付款', value: 'pending' },
  { label: '待完成', value: 'paid' },
  { label: '已完成', value: 'delivered' }
]

// 根据标签筛选订单
const filteredOrders = computed(() => {
  if (activeTab.value === 'all') {
    return orders.value
  } else {
    return orders.value.filter(order => order.status === activeTab.value)
  }
})

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待付款',
    'paid': '待发货',
    'shipped': '待收货',
    'delivered': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 返回个人页面
const goBack = () => {
  router.push('/MyInfo')
}

// 去购物
const goShopping = () => {
  router.push('/petStore')
}

// 查看订单详情
const viewOrderDetail = (order) => {
  router.push({
    path: `/order/detail/${order.ordersId}`,
    query: { orderInfo: JSON.stringify(order) }
  })
}

// 支付订单
const payOrder = (order) => {
  // 将订单数据转换为支付页面需要的格式
  const orderInfo = {
    items: [{
      productId: order.productId,
      name: order.productName,
      price: order.productPrice,
      quantity: order.quantity,
      imageUrl: order.productImageUrl
    }],
    totalPrice: order.totalPrice,
    totalCount: order.quantity,
    discount: 0,
    ordersId: order.ordersId,
    orderNumber: order.orderNumber
  }

  // 跳转到支付页面
  router.push({
    path: '/order/payment',
    query: {
      orderInfo: JSON.stringify(orderInfo)
    }
  })
}

// 确认收货
const confirmReceipt = async (order) => {
  try {
    // 设置确认回调
    confirmDialogText.value = '确认要收货吗？确认后无法撤销'
    confirmCallback.value = async () => {
      const res = await confirmOrder(order.orderNumber)
      if (res.data.code === 200) {
        showToast('确认收货成功')
        await fetchOrders()
      } else {
        showToast(res.message || '确认收货失败')
      }
    }
    showConfirmDialog.value = true

  } catch (error) {
    console.error('确认收货失败:', error)
    showToast('确认收货失败，请稍后再试')
  }
}

// 修改删除订单函数
const openDeleteConfirm = (order) => {
  orderToDelete.value = order.orderNumber
  showDeleteConfirm.value = true
}

const deleteOrder = async () => {
  try {
    if (!orderToDelete.value) return
    console.log('删除订单:', orderToDelete.value)
    // 调用删除订单的API
    const res = await deleteOrderApi(orderToDelete.value);
    console.log('删除订单结果:', res.data)
    await fetchOrders();
    // 关闭删除确认弹窗
    showDeleteConfirm.value = false


  } catch (error) {
    console.error('删除订单失败:', error)
    alert('删除订单失败，请稍后再试')
  }
}

// 获取订单数据
const fetchOrders = async () => {
  loading.value = true
  try {
    // 调用获取订单列表API
    const res = await getOrderList()
    console.log('订单列表数据:', res.data)

    if (res.data && res.data.code === 200) {
      // 直接使用后端返回的数据数组
      orders.value = res.data.data || []
    } else {
      console.error('获取订单列表失败:', res.data?.message || '未知错误')
      orders.value = []
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    orders.value = []
  } finally {
    loading.value = false
  }
}

// 监听标签变化时重新获取数据
watch(activeTab, () => {
  fetchOrders()
})

onMounted(() => {
  fetchOrders()
})

// 添加确认弹窗的处理方法
const handleConfirm = async () => {
  if (confirmCallback.value) {
    await confirmCallback.value()
  }
  showConfirmDialog.value = false
}

// 添加简单的 toast 提示
const showToast = (message) => {
  toast.value.message = message
  toast.value.show = true
  setTimeout(() => {
    toast.value.show = false
  }, 2000)
}
</script>

<style lang="scss" scoped>
.my-orders-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20px;
}

.nav-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background-color: white;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 100;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

  .back-button {
    background: none;
    border: none;
    padding: 8px;
    margin-left: -8px;
    cursor: pointer;
  }

  h2 {
    flex: 1;
    text-align: center;
    margin: 0;
    font-size: 16px;
  }
}

.order-tabs {
  display: flex;
  background-color: white;
  margin-top: 44px;
  overflow-x: auto;
  white-space: nowrap;
  -webkit-overflow-scrolling: touch;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  .tab {
    padding: 12px 16px;
    margin: 0 auto;
    font-size: 14px;
    color: #666;
    position: relative;
    cursor: pointer;

    &.active {
      color: #8B5CF6;
      font-weight: 500;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 20px;
        height: 2px;
        background-color: #8B5CF6;
      }
    }
  }
}

.orders-container {
  padding: 12px;
  margin-top: 8px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;

  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid rgba(139, 92, 246, 0.2);
    border-top-color: #8B5CF6;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 12px;
  }

  .loading-text {
    color: #666;
    font-size: 14px;
  }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.empty-orders {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;

  .empty-icon {
    margin-bottom: 16px;
  }

  .empty-text {
    color: #999;
    font-size: 14px;
    margin-bottom: 20px;
  }

  .go-shopping-btn {
    background-color: #8B5CF6;
    color: white;
    border: none;
    border-radius: 20px;
    padding: 8px 24px;
    font-size: 14px;
    cursor: pointer;

    &:active {
      opacity: 0.9;
    }
  }
}

.order-list {
  .order-card {
    background-color: white;
    border-radius: 8px;
    margin-bottom: 12px;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

    .order-header {
      display: flex;
      justify-content: space-between;
      padding: 12px 16px;
      border-bottom: 1px solid #f0f0f0;

      .order-number {
        font-size: 12px;
        color: #666;
      }

      .order-status {
        font-size: 12px;
        font-weight: 500;

        &.pending {
          color: #f59e0b;
        }

        &.paid {
          color: #3b82f6;
        }

        &.shipped {
          color: #10b981;
        }

        &.completed {
          color: #8B5CF6;
        }

        &.cancelled {
          color: #9ca3af;
        }
      }
    }

    .order-items {
      padding: 0 16px;

      .order-item {
        display: flex;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .item-image {
          width: 60px;
          height: 60px;
          object-fit: cover;
          border-radius: 4px;
          margin-right: 12px;
          border: 1px solid #f0f0f0;
        }

        .item-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;

          .item-name {
            font-size: 14px;
            line-height: 1.4;
            max-height: 40px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
          }

          .item-quantity {
            font-size: 12px;
            color: #999;
          }
        }

        .item-price {
          font-size: 14px;
          color: #ff3b30;
          margin-left: 12px;
          white-space: nowrap;
        }
      }
    }

    .order-footer {
      padding: 12px 16px;
      border-top: 1px solid #f0f0f0;

      .order-total {
        text-align: right;
        font-size: 12px;
        color: #666;
        margin-bottom: 12px;

        .price {
          font-size: 16px;
          font-weight: 500;
          color: #ff3b30;
        }
      }

      .order-actions {
        display: flex;
        justify-content: flex-end;
        gap: 8px;

        .action-btn {
          padding: 6px 12px;
          font-size: 12px;
          border-radius: 16px;
          cursor: pointer;
          background-color: white;

          &.pay-btn {
            color: white;
            background-color: #ff3b30;
            border: none;
          }

          &.confirm-btn {
            color: white;
            background-color: #10b981;
            border: none;
          }

          &.review-btn {
            color: white;
            background-color: #f59e0b;
            border: none;
          }

          &.delete-btn {
            color: #666;
            border: 1px solid #ddd;

            &:hover {
              color: #ff3b30;
              border-color: #ff3b30;
            }
          }

          &.detail-btn {
            color: #666;
            border: 1px solid #ddd;
          }

          &:active {
            opacity: 0.9;
          }
        }
      }
    }
  }
}

.delete-confirm {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;

  .confirm-dialog {
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    width: 80%;
    max-width: 300px;

    h3 {
      margin: 0 0 16px;
      font-size: 16px;
      color: #333;
    }

    p {
      margin: 0 0 20px;
      font-size: 14px;
      color: #666;
      line-height: 1.5;
    }

    .confirm-actions {
      display: flex;
      justify-content: flex-end;
      gap: 12px;

      button {
        padding: 8px 16px;
        border-radius: 4px;
        font-size: 14px;
        cursor: pointer;

        &.cancel-btn {
          background-color: #f5f5f5;
          border: none;
          color: #666;
        }

        &.confirm-btn {
          background-color: #ff3b30;
          border: none;
          color: white;
        }

        &:active {
          opacity: 0.9;
        }
      }
    }
  }
}

.custom-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.custom-dialog {
  background: white;
  border-radius: 8px;
  padding: 20px;
  width: 80%;
  max-width: 300px;

  .dialog-content {
    margin-bottom: 20px;

    p {
      margin: 0;
      font-size: 14px;
      color: #333;
      text-align: center;
    }
  }

  .dialog-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;

    button {
      padding: 8px 16px;
      border-radius: 4px;
      font-size: 14px;
      cursor: pointer;

      &.cancel-btn {
        background: #f5f5f5;
        border: none;
        color: #666;
      }

      &.confirm-btn {
        background: #8B5CF6;
        border: none;
        color: white;
      }
    }
  }
}

.custom-toast {
  position: fixed;
  bottom: 20%;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px 20px;
  border-radius: 4px;
  font-size: 14px;
  z-index: 1000;
}
</style>
